<template>
  <div>
    <div style="display: flex;">
        <searchBuildFloor @treeSelectEmit="handleTreeSelect"></searchBuildFloor>
        <div class="listBox" >
          <div class="btnRow">
                <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls" style="margin-right:10px;"> 导入模板</a-button>
                <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">批量导入</j-upload-button>
          </div>
          <div class="roomItem" v-for="(item,index) in roomList" :key="index">
              <div class="roomName">房间：{{item.roomCode}}</div>
              <div class="bedList">
                  <div class="bedItem" v-for="(item2,index2) in item.details" :key="index2">
                         <div class="info">床铺号:{{item2.bedCode}}</div>

                    <template v-if="item2.name">
                      <div class="infoBox">
                         <div class="info">班级:{{item2.departmentName}}</div>
                         <div class="info">学生:{{item2.name}}</div>
                         <div>
                          <a-button  type="primary" @click="handleStudentDetail(item,item2)" > 查看</a-button>&nbsp;
                          <a-button  type="primary" @click="handleStudentLeave(item,item2)" > 退室</a-button>
                          </div>
                      </div>
                    </template>
                    <template v-if="!item2.name">
                      <div>
                         <div class="info">空</div>
                         <div class="info">
                          <a-button type="primary" @click="handleAddStudent(item,item2)" preIcon="ant-design:plus-outlined"> 安排入住</a-button>
                         </div>
                      </div>
                    </template>
                     
                  </div>
              </div>
          </div>
        </div>
        </div>
        <!-- <div style="width: calc( 100% - 260px )">
          <BasicTable @register="registerTable" :rowSelection="rowSelection">
              <template #tableTitle>
                  <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
                  <a-dropdown v-if="selectedRowKeys.length > 0">
                      <template #overlay>
                        <a-menu>
                          <a-menu-item key="1" @click="batchHandleDelete">
                            <Icon icon="ant-design:delete-outlined"></Icon>
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                      <a-button>批量操作
                        <Icon icon="mdi:chevron-down"></Icon>
                      </a-button>
                </a-dropdown>
              </template>
              <template #action="{ record }">
                <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
              </template>
              <template v-slot:bodyCell="{ column, record, index, text }">
              </template>
          </BasicTable>
        </div>
    </div> -->
    <DormBedPersonModal @register="registerModal" @success="handleSuccess"></DormBedPersonModal>
    <DormBedPersonLeaveModal @register="registerLeaveModal" @success="handleSuccess"></DormBedPersonLeaveModal>
  </div>
</template>

<script lang="ts" name="dormitory-dormBedPerson" setup>
  import {ref, reactive, computed, unref,onMounted} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import DormBedPersonModal from './components/DormBedPersonModal.vue'
  import DormBedPersonLeaveModal from './components/DormBedPersonLeaveModal.vue'
  import {columns, searchFormSchema, superQuerySchema} from './DormBedPerson.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl,detailedList,saveApi} from './DormBedPerson.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import searchBuildFloor from '@/views/dormitory/components/searchBuildFloor.vue';
  // import { identity } from 'vue-types/dist/utils';
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  //注册model
  const [registerModal, {openModal:addModal}] = useModal();
  const [registerLeaveModal, {openModal:leaveModal}] = useModal();
  let selectBedDetail = ref({})
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '宿舍床铺人员安排信息',
           api: list,
           columns,
           canResize:false,
           formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
              fieldMapToTime: [
              ],
            },
           actionColumn: {
               width: 120,
               fixed:'right'
            },
            beforeFetch: (params) => {
              return Object.assign(params, queryParam);
            },
      },
       exportConfig: {
            name:"宿舍床铺人员安排信息模板",
            url: getExportUrl,
            params: queryParam,
          },
          importConfig: {
            url: getImportUrl,
            success: handleSuccess
          },
  })

  const [registerTable, {reload,getForm},{ rowSelection, selectedRowKeys }] = tableContext

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  async function handleTreeSelect(e){
    console.log(e);
    // let { getFieldsValue,setFieldsValue,submit } =  getForm()
    // let data = getFieldsValue()
    let id = e[0].split('_')[1]
    let type = ''
    if(e[0].includes('buildId')){
      type='build'
    }else{
      type='storey'
    }
    getRoomBedList(id,type)
    // console.log(data);
    // await setFieldsValue(data)
    // await submit()
  }
  let roomList = ref([])
  function getRoomBedList(id,type){
    let data = {}
    if(type=='build'){
      data.buildId = id
    }else{
      data.storeyId = id
    }
    detailedList(data).then(res=>{
      roomList.value = res
      console.log(roomList.value);
    })
  }
  onMounted(()=>{
    getRoomBedList()
  })
  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
   /**
    * 新增事件
    */
  function handleAdd() {
     addModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     leaveModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     addModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }

  
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      getRoomBedList()
      // (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
         }
       ]
   }
  function handleStudentDetail(item,item2){
       console.log(item)
       console.log(item2)
       list({
        bedId:item2.id
       }).then(res=>{
          let detailObj = res.records[0]
          handleDetail(detailObj)
       })
   }
   
  function handleStudentLeave(item,item2){
     
       list({
        bedId:item2.id
       }).then(res=>{
          let detailObj = res.records[0]
          detailObj.liveId=item2.liveId
          handleEdit(detailObj)
       })
   }

   function handleAddStudent(item,item2){
      console.log(item)
      console.log(item2)
      // selectBedDetail.value = item
      let record = {}
      record.roomCode = item.roomCode
      record.bedId = item2.id
       addModal(true, {
       record,
       isUpdate: false,
       showFooter: true,
     });
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         }, {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
             placement: 'topLeft',
           }
         }
       ]
   }


</script>

<style lang="less" scoped>
.btnRow{
  width: 100%;
  padding: 10px;
}
.listBox{
  flex:1;
  display: flex;
  flex-wrap: wrap;
  background: #fff;
  margin: 10px;
}
.roomItem{
  margin: 10px;
  width: 430px;
  border: 1px solid #e5e7eb;
  background: #fafafa;
  padding: 5px;
  .roomName{
    color: #000;
    font-size: 26px;
    display: flex;
    align-items: center;
    height: 50px;
    justify-content: center;
   }
    .bedList{
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .bedItem{
        margin: 5px;
        width: 190px;
        background: #fff;
        border: 1px solid #e5e7eb;
        height: 110px;
        padding: 5px;
        .info{
          display: flex;
          justify-content: center;
        }
      }
    }

}

.infoBox{
  display: flex;
  flex-direction: column;
  align-items: center;
}

</style>